require "redis"


class Store

  # redis = Redis.new(database: 2)
  # redis.auth(password) unless password.nil?

  def self.can?(key : String)
    redis = Redis.new(database: 2)
    flag = true
    msg = ""
    if redis.get(key)
      flag = false
      msg = "两分钟之内只能发一条短信"
    else
      h_count = redis.get(key + "hourliy")
      d_count = redis.get(key + "dayliy")

      if h_count && h_count.to_i >= 3
        flag = false
        msg = "一个小时只能发三条短信"
      end

      if d_count && d_count.to_i >= 5
        flag = false
        msg = "一天只能发五条短信"
      end
    end

    return [flag, msg]
  end

  def self.check(key : String, value : String)
    redis = Redis.new(database: 2)
    val = redis.get(key)
    if val
      if val == value
        redis.del(key)
        return [1, "验证成功"]
      else
        return [0, "验证码错误"]
      end
    else
      return [0, "验证码不存在或者已失效"]
    end
  end


  def self.save(key : String, value : String)
    redis = Redis.new(database: 2)
    now = Time.now
    redis.set(key, value)
    redis.expire(key, 120)

    if redis.get(key + "hourliy")
      redis.incr(key + "hourliy")
    else
      redis.incr(key + "hourliy")
      redis.expire(key + "hourliy", 60 * 60)
    end

    if redis.get(key + "dayliy")
      redis.incr(key + "dayliy")
    else
      d_time = now.at_beginning_of_day + Time::Span.new(1,0,0,0)
      span = d_time - now
      redis.incr(key + "dayliy")
      redis.expireat(key + "dayliy", span.to_i)
    end
  end
end
